import type {
  Novel,
  User,
  Chapter,
  Comment,
  VipPackage,
  RecommendationItem,
  UserOperationLog,
  BookshelfItem,
} from "@/types";
import mammoth from "mammoth";

// 模拟用户数据
export const mockUsers: User[] = [
  {
    id: "1",
    email: "admin@example.com",
    nickname: "超级管理员",
    password: "admin123456",
    avatar: "https://avatars.githubusercontent.com/u/1?v=4",
    level: 10,
    vipStatus: "yearly",
    vipExpireDate: "2025-12-31T23:59:59Z",
    balance: 9999,
    readingTime: 48000,
    booksRead: 25,
    role: "admin",
    status: "active",
    lastLoginTime: "2024-01-15T10:30:00Z",
    registerIp: "192.168.1.100",
    totalRecharge: 10000,
    totalConsumption: 1,
    purchasedChapters: [],
    createdAt: "2023-01-15T08:00:00Z",
    updatedAt: "2024-01-15T10:30:00Z",
  },
  {
    id: "2",
    email: "user@example.com",
    nickname: "书虫小王",
    password: "user123456",
    avatar: "https://avatars.githubusercontent.com/u/2?v=4",
    level: 5,
    vipStatus: "monthly",
    vipExpireDate: "2025-02-15T23:59:59Z",
    balance: 1200,
    readingTime: 36000,
    booksRead: 18,
    role: "user",
    status: "active",
    lastLoginTime: "2024-01-14T15:20:00Z",
    registerIp: "192.168.1.101",
    totalRecharge: 2000,
    totalConsumption: 800,
    purchasedChapters: ["chapter-1-10", "chapter-1-15"], // 示例已购买章节
    createdAt: "2023-02-10T08:00:00Z",
    updatedAt: "2024-01-14T15:20:00Z",
  },
  {
    id: "3",
    email: "reader@example.com",
    nickname: "阅读达人",
    password: "reader123",
    avatar: "https://avatars.githubusercontent.com/u/3?v=4",
    level: 7,
    vipStatus: "yearly",
    vipExpireDate: "2025-08-20T23:59:59Z",
    balance: 2500,
    readingTime: 72000,
    booksRead: 45,
    role: "user",
    status: "active",
    lastLoginTime: "2024-01-15T09:45:00Z",
    registerIp: "192.168.1.102",
    totalRecharge: 5000,
    totalConsumption: 2500,
    purchasedChapters: [],
    createdAt: "2022-08-15T10:00:00Z",
    updatedAt: "2024-01-15T09:45:00Z",
  },
  {
    id: "4",
    email: "newbie@example.com",
    nickname: "新手读者",
    password: "newbie2024",
    avatar: "https://avatars.githubusercontent.com/u/4?v=4",
    level: 1,
    vipStatus: "none",
    balance: 1,
    readingTime: 3600,
    booksRead: 2,
    role: "user",
    status: "active",
    lastLoginTime: "2024-01-13T14:30:00Z",
    registerIp: "192.168.1.103",
    totalRecharge: 100,
    totalConsumption: 50,
    purchasedChapters: [],
    createdAt: "2024-01-10T16:00:00Z",
    updatedAt: "2024-01-13T14:30:00Z",
  },
  {
    id: "5",
    email: "banned@example.com",
    nickname: "违规用户",
    password: "banned123",
    avatar: "https://avatars.githubusercontent.com/u/5?v=4",
    level: 3,
    vipStatus: "none",
    balance: 0,
    readingTime: 12000,
    booksRead: 8,
    role: "user",
    status: "banned",
    banReason: "发布违规内容",
    banExpireDate: "2024-02-15T23:59:59Z",
    lastLoginTime: "2024-01-05T11:20:00Z",
    registerIp: "192.168.1.104",
    totalRecharge: 500,
    totalConsumption: 500,
    purchasedChapters: [],
    createdAt: "2023-10-20T12:00:00Z",
    updatedAt: "2024-01-05T11:20:00Z",
  },
  {
    id: "6",
    email: "moderator@example.com",
    nickname: "内容审核员",
    password: "moderator2024",
    avatar: "https://avatars.githubusercontent.com/u/6?v=4",
    level: 8,
    vipStatus: "yearly",
    vipExpireDate: "2024-12-31T23:59:59Z",
    balance: 3000,
    readingTime: 54000,
    booksRead: 32,
    role: "moderator",
    status: "active",
    lastLoginTime: "2024-01-15T08:15:00Z",
    registerIp: "192.168.1.105",
    totalRecharge: 3500,
    totalConsumption: 500,
    purchasedChapters: [],
    createdAt: "2023-05-15T09:00:00Z",
    updatedAt: "2024-01-15T08:15:00Z",
  },
];

// 模拟用户操作记录
export const mockUserOperationLogs: UserOperationLog[] = [
  {
    id: "log1",
    userId: "5",
    operatorId: "1",
    operatorName: "超级管理员",
    type: "ban",
    description: "因发布违规内容被封号30天",
    oldValue: { status: "active" },
    newValue: {
      status: "banned",
      banReason: "发布违规内容",
      banExpireDate: "2024-02-15T23:59:59Z",
    },
    createdAt: "2024-01-16T10:00:00Z",
  },
  {
    id: "log2",
    userId: "2",
    operatorId: "1",
    operatorName: "超级管理员",
    type: "vip_grant",
    description: "赠送月度VIP",
    oldValue: { vipStatus: "none" },
    newValue: { vipStatus: "monthly", vipExpireDate: "2024-02-15T23:59:59Z" },
    createdAt: "2024-01-10T14:30:00Z",
  },
  {
    id: "log3",
    userId: "4",
    operatorId: "6",
    operatorName: "内容审核员",
    type: "recharge",
    description: "新用户奖励充值",
    oldValue: { balance: 0 },
    newValue: { balance: 100 },
    createdAt: "2024-01-10T16:30:00Z",
  },
];

// 模拟小说数据
export const mockNovels: Novel[] = [
  {
    id: "1",
    title: "斗破苍穹",
    author: "天蚕土豆",
    authorId: "author1",
    cover: "https://images.unsplash.com/photo-1481627834876-b7833e8f5570?w=300&h=400&fit=crop",
    description:
      "这里是斗气大陆，没有花俏的魔法，有的，仅仅是繁衍到巅峰的斗气！在这里，斗气就是一切！",
    category: "fantasy",
    status: "completed",
    wordCount: 5400000,
    chapterCount: 1648,
    rating: 4.6,
    ratingCount: 89234,
    viewCount: 12500000,
    favoriteCount: 345678,
    tags: ["玄幻", "热血", "升级流", "经典"],
    isVip: true,
    price: 299,
    createdAt: "2020-03-15T08:00:00Z",
    updatedAt: "2023-08-20T15:30:00Z",
    lastChapterTitle: "大结局：斗帝归来",
    lastChapterTime: "2023-08-20T15:30:00Z",
  },
  {
    id: "7",
    title: "斗罗大陆",
    author: "唐家三少",
    authorId: "author7",
    cover: "https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=300&h=400&fit=crop",
    description:
      "唐门外门弟子唐三，因偷学内门绝学为唐门所不容，跳崖明志时却发现没有死，反而以另外一个身份来到了另一个世界，一个属于武魂的世界，名叫斗罗大陆。这里没有魔法，没有斗气，没有武术，却有神奇的武魂。这里的每个人，在自己六岁的时候，都会在武魂殿中令自己的武魂觉醒。武魂有动物，有植物，有器物，武魂可以辅助人们的日常生活。而其中一些特别出色的武魂却可以用来修炼并进行战斗，这个职业，是斗罗大陆上最为强大，也是最荣耀的职业魂师！\n\n当唐门暗器来到斗罗大陆，当唐三武魂觉醒，他能否在这片武魂的世界再铸唐门的辉煌？",
    category: "fantasy",
    status: "completed",
    wordCount: 8888772,
    chapterCount: 336,
    rating: 4.8,
    ratingCount: 298765,
    viewCount: 45600000,
    favoriteCount: 1234567,
    tags: ["玄幻", "武魂", "穿越", "经典", "唐家三少"],
    isVip: true,
    price: 399,
    createdAt: "2008-12-14T08:00:00Z",
    updatedAt: "2009-12-13T20:00:00Z",
    lastChapterTitle: "第三百三十六章 成神（大结局）",
    lastChapterTime: "2009-12-13T20:00:00Z",
  },
  {
    id: "2",
    title: "完美世界",
    author: "辰东",
    authorId: "author2",
    cover: "https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=300&h=400&fit=crop",
    description:
      "一粒尘可填海，一根草斩尽日月星辰，弹指间天翻地覆。群雄并起，万族林立，诸圣争霸，乱天动地。",
    category: "fantasy",
    status: "ongoing",
    wordCount: 6200000,
    chapterCount: 1890,
    rating: 4.8,
    ratingCount: 156789,
    viewCount: 28900000,
    favoriteCount: 567890,
    tags: ["玄幻", "无敌流", "热血", "经典"],
    isVip: true,
    price: 399,
    createdAt: "2019-05-10T10:00:00Z",
    updatedAt: "2024-01-15T09:00:00Z",
    lastChapterTitle: "第1890章：仙域风云",
    lastChapterTime: "2024-01-15T09:00:00Z",
  },
  {
    id: "3",
    title: "都市之超级医圣",
    author: "叶天南",
    authorId: "author3",
    cover: "https://images.unsplash.com/photo-1576091160399-112ba8d25d1f?w=300&h=400&fit=crop",
    description: "一代医圣重生都市，凭借前世的医术和修为，在都市中纵横捭阖，谱写传奇人生。",
    category: "urban",
    status: "ongoing",
    wordCount: 3200000,
    chapterCount: 980,
    rating: 4.3,
    ratingCount: 45678,
    viewCount: 8900000,
    favoriteCount: 234567,
    tags: ["都市", "医术", "重生", "爽文"],
    isVip: false,
    createdAt: "2022-01-20T12:00:00Z",
    updatedAt: "2024-01-14T20:00:00Z",
    lastChapterTitle: "第980章：医者仁心",
    lastChapterTime: "2024-01-14T20:00:00Z",
  },
  {
    id: "4",
    title: "霸道总裁的小娇妻",
    author: "苏小暖",
    authorId: "author4",
    cover: "https://images.unsplash.com/photo-1544947950-fa07a98d237f?w=300&h=400&fit=crop",
    description: "她是没落千金，他是商界传奇。一场意外的相遇，让两颗心紧紧相依。",
    category: "romance",
    status: "completed",
    wordCount: 1800000,
    chapterCount: 560,
    rating: 4.1,
    ratingCount: 23456,
    viewCount: 5600000,
    favoriteCount: 123456,
    tags: ["言情", "霸总", "甜宠", "现代"],
    isVip: true,
    price: 199,
    createdAt: "2021-06-15T14:00:00Z",
    updatedAt: "2023-12-10T16:30:00Z",
    lastChapterTitle: "大结局：幸福的开始",
    lastChapterTime: "2023-12-10T16:30:00Z",
  },
  {
    id: "5",
    title: "星际争霸之虫族崛起",
    author: "机械师",
    authorId: "author5",
    cover: "https://images.unsplash.com/photo-1446776877081-d282a0f896e2?w=300&h=400&fit=crop",
    description: "穿越到星际时代，成为虫族主宰，统领无数虫族，征战星海，称霸宇宙。",
    category: "scifi",
    status: "ongoing",
    wordCount: 2800000,
    chapterCount: 750,
    rating: 4.5,
    ratingCount: 34567,
    viewCount: 7800000,
    favoriteCount: 189012,
    tags: ["科幻", "星际", "虫族", "征战"],
    isVip: true,
    price: 249,
    createdAt: "2022-08-01T16:00:00Z",
    updatedAt: "2024-01-13T18:00:00Z",
    lastChapterTitle: "第750章：虫族舰队",
    lastChapterTime: "2024-01-13T18:00:00Z",
  },
  {
    id: "6",
    title: "大明锦衣卫",
    author: "历史老王",
    authorId: "author6",
    cover: "https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=300&h=400&fit=crop",
    description: "穿越大明，成为锦衣卫，在朝堂与江湖之间游走，书写不一样的明朝传奇。",
    category: "historical",
    status: "ongoing",
    wordCount: 4100000,
    chapterCount: 1200,
    rating: 4.4,
    ratingCount: 67890,
    viewCount: 11200000,
    favoriteCount: 298765,
    tags: ["历史", "穿越", "锦衣卫", "朝堂"],
    isVip: false,
    createdAt: "2021-03-10T09:00:00Z",
    updatedAt: "2024-01-12T21:00:00Z",
    lastChapterTitle: "第1200章：皇城风云",
    lastChapterTime: "2024-01-12T21:00:00Z",
  },
];

// 模拟章节数据
export const mockChapters: Chapter[] = [
  // 斗破苍穹的章节
  {
    id: "chapter1",
    novelId: "1",
    chapterNumber: 1,
    title: "陨落的天才",
    content:
      "斗之大陆，没有魔法，没有斗气，有的，仅仅是繁衍到巅峰的武魂！\n\n十级之后，便可凝聚斗之气旋，成为一名真正的斗者！斗之气旋，九旋巅峰，之上便是斗者九星！二星斗者，便可凝聚斗之气旋！\n\n每一旋的提升，实力便是以几何数般暴涨！\n\n而要想成为一名真正强者，必须不断的凝聚斗之气旋，并且还要经历雷劫的考验！",
    wordCount: 1580,
    isVip: false,
    price: 0,
    isFree: true,
    createdAt: "2009-04-14T10:00:00Z",
    updatedAt: "2009-04-14T10:00:00Z",
  },
  {
    id: "chapter2",
    novelId: "1",
    chapterNumber: 2,
    title: "斗之气，三段！",
    content:
      '萧炎，萧家的少族长，曾经的天才少年，如今的废物...\n\n"斗之气，三段！级别：低级！"\n\n测验魔石碑之上，显示着萧炎如今的实力，斗之气三段，这个成绩，即便是在乌坦城之中，也足以算做是天才了！\n\n可是，看着台下众人嘲讽的目光，萧炎的心中却是一片苦涩...',
    wordCount: 2140,
    isVip: true,
    price: 5,
    isFree: false,
    createdAt: "2009-04-15T10:00:00Z",
    updatedAt: "2009-04-15T10:00:00Z",
  },

  // 斗罗大陆的章节
  {
    id: "chapter7-0",
    novelId: "7",
    chapterNumber: 0,
    title: "引子",
    content:
      "唐门外门弟子唐三，因偷学内门绝学为唐门所不容，跳崖明志时却发现没有死，反而以另外一个身份来到了另一个世界，一个属于武魂的世界，名叫斗罗大陆。这里没有魔法，没有斗气，没有武术，却有神奇的武魂。这里的每个人，在自己六岁的时候，都会在武魂殿中令自己的武魂觉醒。武魂有动物，有植物，有器物，武魂可以辅助人们的日常生活。而其中一些特别出色的武魂却可以用来修炼并进行战斗，这个职业，是斗罗大陆上最为强大，也是最荣耀的职业魂师！\n\n当唐门暗器来到斗罗大陆，当唐三武魂觉醒，他能否在这片武魂的世界再铸唐门的辉煌？",
    wordCount: 280,
    isVip: false,
    price: 0,
    isFree: true,
    createdAt: "2008-12-14T10:00:00Z",
    updatedAt: "2008-12-14T10:00:00Z",
  },
  {
    id: "chapter7-1",
    novelId: "7",
    chapterNumber: 1,
    title: "斗罗大陆，异界唐三",
    content:
      '圣魂村是诺丁城下属的一个小村子，距离诺丁城二十里。这里民风淳朴，村民们日出而作，日落而息，过着平静的生活。\n\n在村子的最西边，有一间看上去有些破旧的铁匠铺，此时正值正午，烈日当空，但铁匠铺内却传出叮叮当当的打铁声。\n\n"当、当、当——"有节奏的敲击声在铁匠铺内回荡着，火花四溅中，一名看上去只有五、六岁的黑发小孩正在挥舞着一柄与其年龄完全不符的铸造锤，有条不紊的锤击着烧红的铁块。\n\n小孩看上去年纪虽小，但挥动铸造锤时却是有模有样，每一锤落下的位置都是恰到好处，力度控制的也是极为精准。\n\n"唐三。"一个低沉的声音在铁匠铺内响起。\n\n听到声音，小孩停下了手中的动作，将铸造锤放在一旁，转过身来。这是一个极为清秀的小孩，皮肤白皙，五官端正，一双黑色的大眼睛显得格外有神。\n\n"爸爸。"小孩恭敬的叫了一声。\n\n在铁匠铺的角落里，坐着一名看上去三十多岁的男子，男子身材高大，但给人的感觉却有些邋遢，胡子拉碴，头发凌乱，身上散发着浓重的酒气。',
    wordCount: 2680,
    isVip: false,
    price: 0,
    isFree: true,
    createdAt: "2008-12-15T10:00:00Z",
    updatedAt: "2008-12-15T10:00:00Z",
  },
  {
    id: "chapter7-2",
    novelId: "7",
    chapterNumber: 2,
    title: "废武魂与先天满魂力",
    content:
      '素云涛看着唐三，眼中流露出几分赞赏之色，"很好，你的武魂是蓝银草，虽然是废武魂，但你的魂力却是先天满魂力，这在魂师界是极为罕见的。"\n\n"什么是先天满魂力？"唐三问道。\n\n素云涛解释道："每个人觉醒武魂后，都会拥有一定的魂力，魂力的多少决定了这个人未来在魂师道路上能走多远。一般来说，觉醒后拥有一级魂力就已经很不错了，能够修炼成为魂师。而你的魂力是十级，也就是先天满魂力，这意味着你可以直接获得第一个魂环，成为真正的魂师！"\n\n唐三点了点头，虽然不太明白魂环是什么，但听起来似乎是好事。\n\n"不过，"素云涛的语气突然变得有些遗憾，"你的武魂是蓝银草，这是公认的废武魂，即使拥有先天满魂力，恐怕也很难在魂师的道路上有所成就。"\n\n"为什么蓝银草是废武魂？"唐三问道。\n\n"因为蓝银草太普通了，它没有任何攻击力，也没有什么特殊的能力，在魂师的战斗中几乎没有什么用处。不过，"素云涛想了想，"蓝银草武魂也不是完全没有用处，至少可以用来辅助，比如捆绑敌人什么的。"',
    wordCount: 3240,
    isVip: true,
    price: 5,
    isFree: false,
    createdAt: "2008-12-16T10:00:00Z",
    updatedAt: "2008-12-16T10:00:00Z",
  },
  {
    id: "chapter7-3",
    novelId: "7",
    chapterNumber: 3,
    title: "双生武魂",
    content:
      '就在素云涛准备离开的时候，唐三突然问道："大人，如果一个人有两个武魂会怎么样？"\n\n素云涛愣了一下，然后摇头道："不可能，每个人只能有一个武魂，这是铁律。"\n\n"可是，如果真的有呢？"唐三坚持问道。\n\n素云涛看了看唐三，突然意识到了什么，"你是说你有两个武魂？这不可能，让我再检查一下。"\n\n说着，素云涛再次释放出自己的武魂，仔细感应着唐三的情况。\n\n片刻后，素云涛的脸色变得极为凝重，"这，这怎么可能？你真的有两个武魂！"\n\n在素云涛的引导下，唐三的左手中出现了一柄小锤子，锤子通体乌黑，看上去平平无奇，但素云涛却感受到了一股强大的威压。\n\n"这是什么武魂？"素云涛震惊的问道。\n\n"我也不知道，它就是这样出现的。"唐三老实的说道。\n\n素云涛深吸了一口气，"双生武魂，这是传说中的存在！据说，拥有双生武魂的人，未来的成就不可限量！但是，双生武魂也意味着巨大的危险，修炼起来比普通魂师要困难得多。"\n\n"为什么？"唐三问道。\n\n"因为双生武魂需要两套魂环，而获得魂环需要猎杀魂兽，这对双生武魂的魂师来说，危险性是普通魂师的两倍！而且，双生武魂的修炼也更加复杂，稍有不慎就可能走火入魔！"',
    wordCount: 3850,
    isVip: true,
    price: 50000,
    isFree: false,
    createdAt: "2008-12-17T10:00:00Z",
    updatedAt: "2008-12-17T10:00:00Z",
  },
  {
    id: "chapter7-4",
    novelId: "7",
    chapterNumber: 4,
    title: "异界唐三的第一件暗器",
    content:
      "第一集 斗罗世界 第四章 异界唐三的第一件暗器\n\n　　清晨，唐三神清气爽的从山上赶回来做早饭，这段日子以来，因为每天都在使用紫极魔瞳，早上又不断的修炼，紫极魔瞳和以前相比已经有了不小的进步，他的眼里已经能够在十米内看清楚蚊虫拍打翅膀的细微动作。如果不是玄天功没能突破瓶颈，唐三相信，自己在其他各方面的进步会更大。\n\n　　将一块五十公分见方的生铁锻造成拳头大小，那原本似乎是不可能的事，早在半个月前唐三就已经完成了。唐昊教他那种借力用力的锻造锤法，他也能够连续挥出二十四锤，每一锤都准确无误，包括力量的控制。虽然唐昊从来没有夸奖过他什么，但从父亲偶尔流露出满意的目光来看，唐三知道，自己这锤法也算是有所小成了，再想进步，还是要靠不断的练习才行。\n\n　　马上要进家门了，轻轻摸了摸手腕，唐三脸上流露出一丝满足的笑容，他的手腕上，正带着来到这个世界后的第一件作品，而且是所有步骤都是由他自己完成的作品。\n\n　　那是一个袖箭，在当初的唐门来说，袖箭是最普通的机括类暗器了，袖箭的制作关键在于机璜的力量以及本身设计的精巧程度。像唐三制造的袖箭，本身甚至是带保险装置的，绝无误伤的可能。\n\n　　一套袖箭，一般都是三根箭和一个袖筒组成，唐三现在手上带的这个也不例外。而这个袖箭的材料，却正是他耗费了近百天时间锤击出来的那块生铁。\n\n　　当唐三完成唐昊交给的任务，把那块生铁锻造成只有拳头大小的时候，他吃惊的发现，原本杂质众多的生铁竟然变成了一块铁母，真正的铁母。\n\n　　前一世，别说是他，就算是唐门最好的铸造大师，也绝不会这种将普通生铁锻造成铁母的方法。但在这个世界，却成为了现实。这本身就是一件极不可思议的事。而唐三手腕上带着的这筒袖箭，正是由那块铁母制造而成的，完成袖箭的制造，包括三根四寸小箭在内，正好用掉了所有铁母。",
    wordCount: 4200,
    isVip: true,
    price: 50000,
    isFree: false,
    createdAt: "2008-12-18T10:00:00Z",
    updatedAt: "2008-12-18T10:00:00Z",
  },
  {
    id: "chapter7-5",
    novelId: "7",
    chapterNumber: 5,
    title: "大师？师傅？",
    content:
      '第一集 斗罗世界 第五章 大师？师傅？\n\n　　一名至少是魂师的人物向自己道歉，老杰克的虚荣心得到了极大的满足，赶忙摇着双手道："不用道歉，不用道歉。我们也不好。大师，那这孩子就麻烦您了。小三，你跟着大师进去吧，可一定要听话。"\n\n　　唐三点了点头，却并没有开口。\n\n　　之前，就在眼前这位大师阻止门房冲向他的时候，他的左手就已经抬了起来，袖箭上的保险已经打开。如果眼前这位大师的话再晚一步，说不定，那门房咽喉处就会多一根短箭。\n\n　　【唐门玄天宝录总纲，第三条，确定对手是敌人，只要其有取死之道，就不要手下留情，否则只会给自己增添烦恼】\n\n　　在唐三看来，门房向杰克这样的老人动手，再加上他的刻薄，本身就已经有了取死之道。同时，他也有绝对的把握，包括老杰克在内，没有谁会发现那枚袖箭是他发出的。没有证据，谁又能够说是他杀人？唐门的无声袖箭弹速极快，只会有一道影子，又岂是门房那样的货色所能闪躲的。\n\n　　杰克又叮嘱了唐三几句后，这才离去。\n\n　　大师淡淡的看了那门房一眼，"这是第一次，也是最后一次，如有再犯，你就不需要留下来了。"他的声音沙哑中带着平静，但却有一种令人无法反驳的感觉。\n\n　　门房背后冷汗直冒，赶忙连声应和着闪到一旁。\n\n　　大师低头看向唐三，脸上挤出一丝微笑，他面部的肌肉似乎有些僵硬，笑起来的样子令人有些不敢恭维。拉起唐三的手，道："我们进去吧。"',
    wordCount: 3900,
    isVip: true,
    price: 50000,
    isFree: false,
    createdAt: "2008-12-19T10:00:00Z",
    updatedAt: "2008-12-19T10:00:00Z",
  },
];

// 模拟评论数据
export const mockComments: Comment[] = [
  {
    id: "comment1",
    novelId: "1",
    userId: "1",
    userName: "书虫小王",
    userAvatar: "https://avatars.githubusercontent.com/u/1?v=4",
    content: "经典中的经典！斗破苍穹真的是玄幻小说的巅峰之作，萧炎的成长历程太精彩了！",
    rating: 5,
    likeCount: 234,
    replyCount: 12,
    createdAt: "2024-01-10T15:30:00Z",
  },
  {
    id: "comment2",
    novelId: "1",
    userId: "2",
    userName: "阅读达人",
    content: "土豆大大的文笔真的没话说，每个角色都刻画得很生动，特别是药老的形象！",
    rating: 5,
    likeCount: 156,
    replyCount: 8,
    createdAt: "2024-01-09T10:20:00Z",
  },
  {
    id: "comment3",
    novelId: "7",
    userId: "3",
    userName: "斗罗迷",
    userAvatar: "https://avatars.githubusercontent.com/u/3?v=4",
    content: "斗罗大陆永远的神！唐三和小舞的爱情线太感人了，三少大大的世界观设定也很完善！",
    rating: 5,
    likeCount: 567,
    replyCount: 23,
    createdAt: "2024-01-12T14:20:00Z",
  },
  {
    id: "comment4",
    novelId: "7",
    userId: "4",
    userName: "武魂研究者",
    userAvatar: "https://avatars.githubusercontent.com/u/4?v=4",
    content: "武魂系统设定太棒了！从蓝银草到昊天锤的双生武魂，唐三的成长之路充满惊喜！",
    rating: 5,
    likeCount: 432,
    replyCount: 18,
    createdAt: "2024-01-11T09:15:00Z",
  },
  {
    id: "comment5",
    novelId: "7",
    userId: "5",
    userName: "魂师学院",
    userAvatar: "https://avatars.githubusercontent.com/u/5?v=4",
    content: "史莱克七怪的友情真的太感动了！每个人的武魂都很有特色，团队配合也很精彩！",
    rating: 4,
    likeCount: 298,
    replyCount: 15,
    createdAt: "2024-01-08T16:45:00Z",
  },
];

// 模拟VIP套餐数据
export const mockVipPackages: VipPackage[] = [
  {
    id: "vip1",
    name: "月度VIP",
    duration: 30,
    price: 29.9,
    originalPrice: 39.9,
    benefits: ["免费阅读所有VIP章节", "每日赠送100书币", "专属VIP标识", "优先客服支持"],
  },
  {
    id: "vip2",
    name: "季度VIP",
    duration: 90,
    price: 79.9,
    originalPrice: 119.7,
    benefits: [
      "免费阅读所有VIP章节",
      "每日赠送150书币",
      "专属VIP标识",
      "优先客服支持",
      "专属阅读背景",
    ],
    isPopular: true,
  },
  {
    id: "vip3",
    name: "年度VIP",
    duration: 365,
    price: 299.9,
    originalPrice: 478.8,
    benefits: [
      "免费阅读所有VIP章节",
      "每日赠送200书币",
      "专属VIP标识",
      "优先客服支持",
      "专属阅读背景",
      "生日专属礼包",
      "年度阅读报告",
    ],
  },
];

// 模拟推荐数据
export const mockRecommendations: RecommendationItem[] = [
  {
    novel: mockNovels[1],
    score: 0.95,
    reason: "因为您喜欢玄幻类小说",
    type: "similar",
  },
  {
    novel: mockNovels[6], // 斗罗大陆
    score: 0.98,
    reason: "经典玄幻巨作，唐家三少代表作",
    type: "popular",
  },
  {
    novel: mockNovels[4],
    score: 0.88,
    reason: "最近热门推荐",
    type: "popular",
  },
  {
    novel: mockNovels[5],
    score: 0.82,
    reason: "最新上架作品",
    type: "new",
  },
];

// 模拟API延迟
export const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/**
 * 根据分类获取小说列表
 */
export const getNovelsByCategory = async (category?: string) => {
  await delay(500);
  if (!category) return mockNovels;
  return mockNovels.filter((novel) => novel.category === category);
};

/**
 * 根据ID获取小说详情
 */
export const getNovelById = async (id: string) => {
  await delay(300);
  return mockNovels.find((novel) => novel.id === id);
};

/**
 * 获取小说章节列表
 */
export const getChaptersByNovelId = async (novelId: string) => {
  await delay(400);
  return mockChapters.filter((chapter) => chapter.novelId === novelId);
};

/**
 * 获取章节内容
 */
export const getChapterById = async (id: string) => {
  await delay(200);
  return mockChapters.find((chapter) => chapter.id === id);
};

/**
 * 获取小说评论
 */
export const getCommentsByNovelId = async (novelId: string) => {
  await delay(300);
  return mockComments.filter((comment) => comment.novelId === novelId);
};

/**
 * 获取推荐小说
 */
export const getRecommendations = async (userId?: string) => {
  await delay(600);
  return mockRecommendations;
};

/**
 * 搜索小说
 */
export const searchNovels = async (keyword: string) => {
  await delay(500);
  return mockNovels.filter(
    (novel) =>
      novel.title.includes(keyword) ||
      novel.author.includes(keyword) ||
      novel.description.includes(keyword) ||
      novel.tags.some((tag) => tag.includes(keyword)),
  );
};

/**
 * 获取热门小说
 */
export const getPopularNovels = async () => {
  await delay(400);
  return [...mockNovels].sort((a, b) => b.viewCount - a.viewCount);
};

/**
 * 获取最新更新小说
 */
export const getLatestNovels = async () => {
  await delay(400);
  return [...mockNovels].sort(
    (a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
  );
};

/**
 * 获取用户书架
 */
export const getUserBookshelf = async (userId: string) => {
  await delay(400);

  // 模拟书架数据 - 用用户ID的简单转换来确定哪些小说在书架中
  const bookshelfNovels = mockNovels.slice(0, 6); // 取前6本作为书架数据

  return bookshelfNovels.map(
    (novel, index): BookshelfItem => ({
      id: `bookshelf_${userId}_${novel.id}`,
      userId: userId,
      novelId: novel.id,
      novel: novel,
      status: (index < 2 ? "reading" : index < 4 ? "favorite" : "finished") as
        | "reading"
        | "finished"
        | "favorite",
      lastReadChapterId:
        index < 4 ? `chapter_${novel.id}_${Math.floor(Math.random() * 10) + 1}` : undefined,
      lastReadTime:
        index < 4
          ? new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
          : undefined,
      readProgress:
        index < 2
          ? Math.floor(Math.random() * 80) + 10
          : index < 4
            ? Math.floor(Math.random() * 50)
            : 100,
      createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      updatedAt: new Date().toISOString(),
    }),
  );
};

/**
 * 添加小说到书架
 */
export const addNovelToBookshelf = async (userId: string, novelId: string) => {
  await delay(300);
  // 模拟添加成功
  return true;
};

/**
 * 从书架移除小说
 */
export const removeNovelFromBookshelf = async (userId: string, novelId: string) => {
  await delay(300);
  // 模拟移除成功
  return true;
};

/**
 * 更新书架项目状态
 */
export const updateBookshelfItemStatus = async (
  bookshelfItemId: string,
  status: "reading" | "finished" | "favorite",
) => {
  await delay(200);
  // 模拟更新成功
  return true;
};

/**
 * 记录阅读历史
 */
export const recordReadingHistory = async (
  userId: string,
  novelId: string,
  chapterId: string,
  duration: number = 0,
) => {
  await delay(200);
  // 模拟记录成功
  return true;
};

/**
 * 解析小说文件内容，支持TXT和DOCX格式
 */
export const parseNovelFile = async (file: File, onProgress?: (progress: number) => void) => {
  console.log("开始解析文件:", file.name);
  console.log("文件类型:", file.type);
  console.log("文件大小:", (file.size / 1024 / 1024).toFixed(2) + "MB");

  try {
    let content: string;
    let chapterIndex: Array<{ title: string; start: number; end: number }> = [];

    // 根据文件类型选择不同的解析方式
    if (file.name.toLowerCase().endsWith(".docx") || file.type.includes("wordprocessingml")) {
      // Word文档解析
      console.log("检测到Word文档，使用mammoth解析");
      onProgress?.(10);

      try {
        const result = await mammoth.extractRawText({ arrayBuffer: await file.arrayBuffer() });
        content = result.value;
        console.log("Word文档解析成功，内容长度:", content.length);
        onProgress?.(30);

        // 对于Word文档，使用传统方式解析章节
        const lines = content.split("\n").map((line) => line.trim());
        const chapterPatterns = [
          /^第[一二三四五六七八九十百千万\d]+章.*$/,
          /^第[一二三四五六七八九十百千万\d]+回.*$/,
          /^章节[一二三四五六七八九十百千万\d]+.*$/,
          /^[一二三四五六七八九十百千万]、.*$/,
          /^\d+\..*$/,
          /^Chapter\s*\d+.*$/i,
        ];

        const chapterLines: { title: string; startIndex: number }[] = [];
        lines.forEach((line, index) => {
          const isChapter = chapterPatterns.some((pattern) => pattern.test(line));
          if (isChapter) {
            chapterLines.push({
              title: line,
              startIndex: index,
            });
          }
        });

        // 转换为字符位置索引
        const charPos = 0;
        chapterIndex = chapterLines.map((chapter, i) => {
          const lineStart = chapter.startIndex;
          const lineEnd =
            i < chapterLines.length - 1 ? chapterLines[i + 1].startIndex : lines.length;

          // 计算字符位置
          const start = lines.slice(0, lineStart).join("\n").length + (lineStart > 0 ? 1 : 0);
          const end =
            i < chapterLines.length - 1
              ? lines.slice(0, lineEnd).join("\n").length + (lineEnd > 0 ? 1 : 0)
              : content.length;

          return {
            title: chapter.title,
            start,
            end,
          };
        });

        onProgress?.(60);
      } catch (error) {
        console.error("Word文档解析失败:", error);
        throw new Error(`Word文档解析失败: ${error instanceof Error ? error.message : "未知错误"}`);
      }
    } else {
      // TXT文件使用Web Worker分块解析
      console.log("检测到文本文件，使用Web Worker分块解析");
      onProgress?.(10);

      try {
        // 创建Web Worker
        const worker = new Worker("/chapter-parser-worker.js");

        const result = await new Promise<Array<{ title: string; start: number; end: number }>>(
          (resolve, reject) => {
            worker.onmessage = (e) => {
              const { type, progress, chapterIndex: chapters, error } = e.data;

              if (type === "progress") {
                // 将Worker进度映射到10-60%范围
                onProgress?.(10 + progress * 50);
              } else if (type === "complete") {
                resolve(chapters);
              } else if (type === "error") {
                reject(new Error(error));
              }
            };

            worker.onerror = (error) => {
              reject(new Error(`Worker错误: ${error.message}`));
            };

            // 发送文件给Worker处理
            worker.postMessage({
              file,
              chunkSize: 1024 * 1024, // 1MB chunks
            });
          },
        );

        chapterIndex = result;
        worker.terminate();

        onProgress?.(60);

        // 读取完整内容用于后续处理
        content = await new Promise<string>((resolve, reject) => {
          const reader = new FileReader();
          reader.onload = (e) => {
            const result = e.target?.result as string;
            if (result) {
              resolve(result);
            } else {
              reject(new Error("文件读取失败"));
            }
          };
          reader.onerror = () => reject(new Error("文件读取失败"));
          reader.readAsText(file);
        });
      } catch (error) {
        console.error("文本文件解析失败:", error);
        throw new Error(`文本文件解析失败: ${error instanceof Error ? error.message : "未知错误"}`);
      }
    }

    onProgress?.(70);

    // 从文件名提取小说标题
    const title = file.name.replace(/\.(txt|TXT|docx|DOCX)$/i, "") || `未命名小说_${Date.now()}`;
    const author = "未知作者";

    console.log("章节识别完成，共找到:", chapterIndex.length, "章");
    console.log(
      "找到的章节标题:",
      chapterIndex.map((ch) => ch.title),
    );

    if (chapterIndex.length === 0) {
      console.log("未找到章节标题，将整个文件作为单章节处理");
      chapterIndex = [
        {
          title: "正文",
          start: 0,
          end: content.length,
        },
      ];
    }

    onProgress?.(80);

    // 生成章节数据
    const chapters = chapterIndex.map((chapterInfo, index) => {
      const chapterContent = content.slice(chapterInfo.start, chapterInfo.end).trim();
      const wordCount = chapterContent.length;

      return {
        title: chapterInfo.title,
        content: chapterContent,
        wordCount,
        chapterNumber: index + 1,
        isVip: index > 2, // 前3章免费
        price: index > 2 ? 50000 : 0,
        isFree: index <= 2,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
    });

    onProgress?.(90);

    // 计算总字数
    const totalWordCount = chapters.reduce((sum, chapter) => sum + chapter.wordCount, 0);

    const result = {
      novel: {
        title,
        author,
        description: `《${title}》是一部精彩的小说作品，共${chapters.length}章，总计${totalWordCount.toLocaleString()}字。`,
        category: "fantasy" as const,
        status: "ongoing" as const,
        wordCount: totalWordCount,
        chapterCount: chapters.length,
        coverUrl: "https://picsum.photos/400/600?random=" + Date.now(),
        tags: ["热血", "冒险", "成长"],
        isVip: false,
        price: 0,
        rating: 4.5,
        viewCount: 0,
        favoriteCount: 0,
        commentCount: 0,
        lastChapterTitle: chapters[chapters.length - 1]?.title || "",
        lastUpdateTime: new Date().toISOString(),
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      },
      chapters,
    };

    onProgress?.(100);
    console.log("文件解析完成:", result);

    return result;
  } catch (error) {
    console.error("文件解析失败:", error);
    throw error;
  }
};

/**
 * 创建新小说
 */
export const createNovel = async (novelData: {
  title: string;
  author: string;
  description: string;
  category: string;
  wordCount: number;
  chapterCount: number;
  authorId: string;
}) => {
  await delay(500);

  // 生成新的小说ID
  const newId = (mockNovels.length + 1).toString();

  const newNovel: Novel = {
    id: newId,
    title: novelData.title,
    author: novelData.author,
    authorId: novelData.authorId,
    cover: `https://images.unsplash.com/photo-${Date.now()}?w=300&h=400&fit=crop`,
    description: novelData.description,
    category: novelData.category as any,
    status: "ongoing",
    wordCount: novelData.wordCount,
    chapterCount: novelData.chapterCount,
    rating: 0,
    ratingCount: 0,
    viewCount: 0,
    favoriteCount: 0,
    tags: ["新作品"],
    isVip: false,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };

  // 添加到模拟数据中
  mockNovels.push(newNovel);

  return newNovel;
};

/**
 * 创建章节
 */
export const createChapters = async (
  novelId: string,
  chapters: {
    title: string;
    content: string;
    wordCount: number;
  }[],
) => {
  await delay(800);

  const createdChapters = chapters.map((chapter, index) => ({
    id: `${novelId}_${index + 1}`,
    novelId,
    title: chapter.title,
    content: chapter.content,
    wordCount: chapter.wordCount,
    chapterNumber: index + 1,
    isVip: false,
    isFree: true,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  }));

  return createdChapters;
};
